package org.framework.lazy.cloud.network.heartbeat.protocol.utils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.handler.codec.http.FullHttpRequest;

import java.util.Map;

public class FullHttpRequestUtils {

    public static final String RETURN_LINE = "\r\n";

    /**
     * 将  FullHttpRequest 转换成 ByteBuf 发送下一个通道
     *
     * @param request FullHttpRequest
     * @return ByteBuf
     */
    public static ByteBuf toByteBuf(FullHttpRequest request) {
        // TODO CompositeByteBuf
        ByteBuf body = PooledByteBufAllocator.DEFAULT.buffer();
        // request-line
        body.writeBytes(request.method().asciiName().toByteArray());
        body.writeBytes(" ".getBytes());
        body.writeBytes(request.uri().getBytes());
        body.writeBytes(" ".getBytes());
        body.writeBytes(request.protocolVersion().protocolName().getBytes());
        body.writeBytes(("/" + request.protocolVersion().majorVersion() + "." + request.protocolVersion().minorVersion()).getBytes());
        body.writeBytes(RETURN_LINE.getBytes());
        // request-header
        for (Map.Entry<String, String> header : request.headers()) {
            body.writeBytes(header.getKey().getBytes());
            body.writeBytes(":".getBytes());
            body.writeBytes(header.getValue().getBytes());
            body.writeBytes(RETURN_LINE.getBytes());
        }
        body.writeBytes(RETURN_LINE.getBytes());
        // request-body
        if (request.content() != null) {
            body.writeBytes(request.content());
        }

        return body;
    }
}
